

import { Button, Form, Input, Modal, Space, Switch, Table, message } from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { getDBListPageApi, addDBList, getDBListDetail, updateListDetail, removeDBListById } from '@/api/root'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';


const Home: React.FC = () => {
    const [confirmLoading, setconfirmLoading] = useState(false)
    const [total, setTotal] = useState(0)
    const [pagenation, setPagenation] = useState<GetDBListPage.Request>({
        page: 1,
        pageSize: 5
    })
    const [DBListPage, setDBListPage] = useState<GetDBListPage.Record[]>([])
    const AETableModalRef = useRef<AETableModalRef>(null)
    const Nav = useNavigate()
    // 获取表名列表
    const getDBListPage = async () => {
        const res = await getDBListPageApi(pagenation)
        if (res.code !== 1) return;
        setTotal(res.data.total ?? 0)
        setDBListPage(res.data.records ?? [])
    }
    // 打开新建表
    const openAETableModal = (title: string, uId?: string) => {
        AETableModalRef.current?.openModal(title, uId)
    }
    // 确认添加
    const afterModalConfirm: AETableModalPrpos['afterModalConfirm'] = async (formData, titleModal) => {
        setconfirmLoading(true)
        console.log(formData);
        if (titleModal === '新建表') {
            const res = await addDBList(formData)
            setconfirmLoading(false)
            if (res.code !== 1) return
            message.success('新建成功')
            getDBListPage()
            AETableModalRef.current?.closeModal()
        } else {
            const res = await updateListDetail(formData as UpdateListDetail.Request)
            setconfirmLoading(false)
            if (res.code !== 1) return
            message.success('更新成功')
            getDBListPage()
            AETableModalRef.current?.closeModal()
        }
    }
    // 确认删除
    const confirmDelete = (uId: string) => {
        Modal.confirm({
            title: '是否确认删除',
            icon: <ExclamationCircleOutlined />,
            okType: 'danger',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                const res = await removeDBListById({ uId })
                if (res.code !== 1) return
                getDBListPage()
                message.success('删除成功')
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    // 表格发送变化
    const tableChange: TableProps<GetDBListPage.Record>['onChange'] = (pagination) => {
        setPagenation(() => Object.assign({}, { page: pagination.current, pageSize: pagination.pageSize }))
    }
    // 跳转详情页面
    const goToDetail = (uId: string) => {
        Nav(`/detail?uId=${uId}`)
    }
    useEffect(() => {
        getDBListPage()
    }, [pagenation])
    const columns: ColumnsType<GetDBListPage.Record> = [
        {
            title: '表名',
            dataIndex: 'title',
            key: 'title',
            render: text => <a>{text}</a>,
        },
        {
            title: '表名(英文)',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '接口数量',
            dataIndex: 'apiList',
            key: 'apiList',
            render: (_, { apiList }) => <span>{apiList?.length}</span>,
        },
        {
            title: '操作',
            width: '200px',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button size='small' type='primary' onClick={() => openAETableModal('编辑表', record.uId)}>编辑</Button>
                    <Button size='small' type='primary' onClick={() => goToDetail(record.uId)}>详情</Button>
                    <Button size='small' danger onClick={() => confirmDelete(record.uId)}>删除</Button>
                </Space>
            ),
        },
    ];
    return (<>
        <div>
            <Button type='primary' style={{ margin: '10px 0' }} onClick={() => openAETableModal('新建表')}>新建表</Button>
            <Table onChange={tableChange} rowKey='uId' columns={columns} dataSource={DBListPage} pagination={{ total: total, current: pagenation.page, pageSize: pagenation.pageSize }} />
            <AETableModal confirmLoading={confirmLoading} ref={AETableModalRef} afterModalConfirm={afterModalConfirm}></AETableModal>
        </div >
    </>)
}
interface AETableModalPrpos {
    afterModalConfirm: (formData: AddDBList.Request | UpdateListDetail.Request, titleModal: string) => void
    confirmLoading: boolean
}
interface AETableModalRef {
    openModal: (title: string, uId?: string) => void
    closeModal: () => void
}
// 新建表/编辑表
const AETableModal = React.forwardRef<AETableModalRef, AETableModalPrpos>((props, ref) => {
    const { afterModalConfirm, confirmLoading } = props
    const [isModalOpen, setisModalOpen] = useState(false)
    const [titleModal, settitleModal] = useState('')
    const [uId, setuId] = useState<string>()
    const defaultFormData = {
        name: '',
        isPremission: false,
        title: ''
    }
    const [formData, setformData] = useState<AddDBList.Request>(defaultFormData)
    const [form] = Form.useForm();
    const handleOk = () => {
        form
            .validateFields()
            .then(values => {
                afterModalConfirm({ uId, ...Object.assign(formData, values) }, titleModal);
            })
            .catch(info => {
                console.log('Validate Failed:', info);
            });
    }
    const handleCancel = () => {
        form.resetFields();
        setisModalOpen(false)
    }
    const openModal: AETableModalRef['openModal'] = async (title, uId) => {
        settitleModal(title)
        setuId(uId)
        if (uId && uId !== '') {
            const res = await getDBListDetail({ uId })
            if (res.code !== 1) return;
            setformData({
                name: res.data.name!,
                isPremission: res.data.isPremission!,
                title: res.data.title!
            })
            form.setFieldsValue(res.data)
            setisModalOpen(true)
        } else {
            setisModalOpen(true)
            form.setFieldValue('isPremission', defaultFormData.isPremission)
        }

    }
    useImperativeHandle(ref, () => ({
        openModal,
        closeModal: handleCancel
    }))
    return (<>
        <Modal confirmLoading={confirmLoading} title={titleModal} open={isModalOpen} okText='提交' cancelText='取消' onOk={handleOk} onCancel={handleCancel}>
            <Form
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                form={form}
            >
                <Form.Item
                    label="表名（中文）"
                    name="title"
                    rules={[{ required: true, message: '请输入中文表名!', pattern: /^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/ }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="表名（英文）"
                    name="name"
                    rules={[{ required: true, message: '请输入英文表名!', pattern: /^[a-zA-Z]+$/ }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="是否加权限"
                    name="isPremission"
                >
                    <Switch checked={formData.isPremission} onChange={(checked) => {
                        setformData((val) => {
                            return Object.assign({}, { ...val, isPremission: checked })
                        })
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    </>)
})
export default Home
